package com.smile.chatview;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JButton;

public class BasicButton extends JButton {

	/** 
     *  
     */
	private static final long serialVersionUID = 1L;
	public static final Color BUTTON_FOREGROUND_COLOR = Color.BLACK;
	private Color[] color = { new Color(48, 57, 66), new Color(54, 63, 72) };
	private boolean hover = false;
	private boolean click = false;
	private BufferedImage[] images;

	public BasicButton(String text, String[] imgNames) {
		super(text);
		try {
			images = new BufferedImage[2];
			images[0] = ImageIO.read(new File("resources/img/" + imgNames[0]));
			images[1] = ImageIO.read(new File("resources/img/" + imgNames[1]));
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 步骤1
		setBorderPainted(false);
		setFocusPainted(false);
		setContentAreaFilled(false);

		setForeground(BUTTON_FOREGROUND_COLOR);
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				hover = true;
				repaint();
			}

			@Override
			public void mouseExited(MouseEvent e) {
				hover = false;
				repaint();
			}

			@Override
			public void mouseClicked(MouseEvent e) {
				hover = true;
				click = !click;
				repaint();
			}
		});
	}

	public void setClick(boolean click) {
		this.click = click;
		repaint();
	}

	@Override
	protected void paintComponent(Graphics g) {

		Graphics2D g2d = (Graphics2D) g;
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		if (hover || click) {
			g2d.setColor(color[1]);
		} else {
			g2d.setColor(color[0]);
		}
		g2d.fillRect(0, 0, getWidth(), getHeight());

		if (hover || click) {
			if (images[1] != null) {
				g2d.drawImage(images[1], getWidth() / 2 - 20, 5, 40, 40, null);
			}
		} else {
			if (images[0] != null) {
				g2d.drawImage(images[0], getWidth() / 2 - 20, 5, 40, 40, null);
			}
		}

		super.paintComponent(g);
	}
}